/**
 * Copyright (c) 2016-2023, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.web.sitemap;

import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jpress.JPressOptions;

import java.util.Date;
import java.util.List;

@RequestMapping("/sitemap")
public class SitemapController extends JbootController {


    private static final String contentType = "text/xml; charset=utf-8";

    public void index() {

        boolean siteMapEnable = JPressOptions.isTrueOrEmpty("seo_sitemap_enable");
        if (!siteMapEnable) {
            renderError(404);
            return;
        }


        StringBuilder xmlBuilder = new StringBuilder();

        List<SitemapProvider> providers = SitemapManager.me().getProviders();

        buildUrlsetHeader(xmlBuilder);

        //首页 sitemap
        Sitemap index = new Sitemap();
        index.setLoc("/");
        index.setChangefreq(Sitemap.CHANGEFREQ_ALWAYS);
        index.setLastmod(new Date());
        index.setPriority(1F);
        xmlBuilder.append(index.toXml());


        providers.forEach(provider -> {
            List<Sitemap> sitemaps = provider.getSitemaps();
            if (sitemaps != null) {
                sitemaps.forEach(sitemap -> xmlBuilder.append(sitemap.toXml()));
            }
        });


        buildUrlsetFooter(xmlBuilder);

        renderText(xmlBuilder.toString(), contentType);
    }


    private void buildUrlsetHeader(StringBuilder xmlBuilder) {
        buildHeader(xmlBuilder);
        xmlBuilder.append("<sitemapindex");
        xmlBuilder.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
        xmlBuilder.append(" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\" ");
        xmlBuilder.append(" xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" ");
        xmlBuilder.append(" > ");
    }


    private void buildUrlsetFooter(StringBuilder xmlBuilder) {
        xmlBuilder.append("</sitemapindex>");
        buildFooter(xmlBuilder);
    }


    private void buildHeader(StringBuilder xmlBuilder) {
        xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    }

    private void buildFooter(StringBuilder xmlBuilder) {
        xmlBuilder.append("<!-- This sitemap was generated by JPress --> ");
    }

}
